package com.googlecode.perfectable.visuable.webchat.ui;

import com.googlecode.perfectable.introspection.Injection;
import com.googlecode.perfectable.introspection.Injection.CompositeInjection;
import com.googlecode.perfectable.visuable.configuration.StandardConfigurator;
import com.googlecode.perfectable.visuable.event.Event;
import com.googlecode.perfectable.visuable.event.EventListener;
import com.googlecode.perfectable.visuable.visual.Visual;
import com.googlecode.perfectable.visuable.visual.controller.Controller;
import com.googlecode.perfectable.webchat.ChatService;
import com.googlecode.perfectable.webchat.MemoryChatService;

public class ChatConfigurator extends StandardConfigurator {

	private final ChatService service = new MemoryChatService();

	private final CompositeInjection<Object> injections;

	public ChatConfigurator() {
		Injection<Object> chatServiceInjection = Injection.create(Object.class, "chatService",
				ChatService.class, this.service);
		this.injections = Injection.createComposite(chatServiceInjection);
	}

	@Override
	public <C extends Visual, T extends Controller<? super C>> T createController(Class<T> controllerClass,
			Class<C> visualClass) {
		final T controller = super.createController(controllerClass, visualClass);
		this.injectServices(controller);
		return controller;
	}

	@Override
	public <E extends Event, T extends EventListener<? super E>> T createListener(Class<T> listenerClass,
			Class<E> eventClass) {
		final T listener = super.createListener(listenerClass, eventClass);
		this.injectServices(listener);
		return listener;
	}

	private void injectServices(Object target) {
		this.injections.perform(target);
	}
}
